/**
 * Copyright (c) 2014-2015, Suredy technology Co., Ltd. All rights reserved.
 * 
 * @author ZhangMaoren
 * @since 2015年4月8日
 * @version 0.1
 */
package com.suredy.component;

/**
 * @author ZhangMaoren
 *
 */
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.suredy.Constants;


public class Uploader extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -243834751364760535L;

	private File storeagePath;

	private File tempPath;

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String appName = req.getParameter("app");
		//存储目录
		String basePath = new File(getServletContext().getRealPath("upload")).getAbsolutePath();
		// 临时目录
		tempPath = new File(basePath + File.separator + "temp");
		if (!tempPath.exists()) {
			tempPath.mkdir();
		}
		storeagePath = new File(basePath + File.separator + appName + File.separator + Constants.datetimeFormater.format(new Date()));
		if (!storeagePath.exists()) {
			storeagePath.mkdir();
		}

		
		
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 设置文件的下限
		factory.setSizeThreshold(4 * 1024);
		// 设置中转目录
		factory.setRepository(tempPath);

		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UFT-8");
		// 设置上传文件的上限
		upload.setSizeMax(1024 * 1024 * 512);
		StringBuffer sb = new StringBuffer();
		try {
			List<FileItem> fileItems = upload.parseRequest(req);
			for (Iterator<FileItem> iter = fileItems.iterator(); iter.hasNext();) {
				FileItem item =  iter.next();
				// 是否为input="type"输入域
				if (!item.isFormField()) {
					String fileName = item.getName();
					long size = item.getSize();
					if ((fileName == null || fileName.equals("")) && size == 0) {
						continue;
					}
					// 截取字符串 如：C:\WINDOWS\Debug\PASSWD.LOG
					fileName = fileName.substring(fileName.lastIndexOf(File.separator) + 1, fileName.length());
					File storeageFile = new File(storeagePath, fileName);
					item.write(new File(storeagePath, fileName));
					sb.append(",").append("/upload" + storeageFile.getAbsolutePath().substring(basePath.length()).replace(File.separator, "/") );
					//TODO
				} else {
					//TODO 普通文本域
					continue;
				}
			}
			resp.reset();
			resp.setContentType("application/json; charset=utf-8");  
			resp.getWriter().write("{\"path\":\""+ sb.substring(1) +"\"}");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		doPost(req, res);
	}

}
